﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace InSTEDD.Labs.Geo.GeoCoding.Google
{
	public sealed class GoogleGeoCoder : IGeoCoder
	{
		String googleKey;
		bool initialized = false;
		String GoogleGeoCoderUrl = "http://maps.google.com/maps/geo?q={0}&output=csv&key={1}";

		#region IGeoCoder Members

		public InSTEDD.Labs.Geo.LatLong GetLatLongFromPostalAddress(string postalAddress)
		{
			if (!initialized)
			{
				// TODO: move to SR
				throw new Exception("GoogleGeoCoder needs to be initialized before used");
			}

			String url = String.Format(GoogleGeoCoderUrl, postalAddress, googleKey);
			WebRequest webRequest = HttpWebRequest.Create(url);
			HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;

			if (webResponse.StatusCode != HttpStatusCode.OK)
			{
				return null;
			}

			StreamReader webstream = new StreamReader(webResponse.GetResponseStream(), Encoding.ASCII);
			String temp; StringBuilder sb = new StringBuilder();
			while ((temp = webstream.ReadLine()) != null)
			{
				sb.Append(temp);
			}

			String[] parts = sb.ToString().Split(',');
			if (parts[0] == "200")
			{
				return LatLong.Parse(parts[2], parts[3]);
			}

			return null;
		}

		public void Initialize(object initData)
		{
			googleKey = initData as String;

			if (String.IsNullOrEmpty(googleKey))
			{
				throw new ArgumentNullException("initData");
			}

			initialized = true;
		}

		#endregion
	}
}
